/**
 * Created by keen on 2017/8/10.
 */

package keenabc

import (
	"os"
	"strings"
	"io/ioutil"
)

func ReadRouter(structName string, flags []string, PackageName string) {

	base := false
	modal := false
	json := false
	for i := 0; i < len(flags); i++ {
		if flags[i] == "1" {
			base = true
		} else if flags[i] == "2" {
			json = true
		} else if flags[i] == "3" {
			modal = true
		}

	}

	var fileContent string

	path, _ := os.Getwd()
	content, err := ioutil.ReadFile(path+"/routers/router.go")
	router, _ := os.OpenFile(path+"/routers/router.go" , os.O_CREATE|os.O_RDWR, 0766)

	if err != nil {

	}
	lines := strings.Split(string(content), "\n")
	for _, v := range lines {
		fileContent += v + "\n"
		if base {
			if strings.Contains(v, "//system-begin") {
				fileContent += "	beego.Router(\"/" + structName + "\", &"+PackageName+"."+ structName +"Controller{})\n"
				fileContent += "	beego.AutoRouter(&"+PackageName+"."+ structName +"Controller{})\n"
			}
		}
		if json {
			if strings.Contains(v, "//api-begin") {
				fileContent += "	beego.Router(\"/" + structName + "json\", &"+PackageName+"."+ structName +"JsonController{})\n"
				fileContent += "	beego.AutoRouter(&"+PackageName+"."+ structName +"JsonController{})\n"
			}
		}
		if modal {
			if strings.Contains(v, "//modal-begin") {
				fileContent += "	beego.Router(\"/"+ structName +"modal\", &"+PackageName+"."+structName+"ModalController{})\n"
				fileContent += "	beego.AutoRouter(&"+PackageName+"."+structName+"ModalController{})\n"
			}
		}
	}

	router.WriteString(fileContent)
}

func GenerateController(controllername string, flags []string) {
	path, _ := os.Getwd()

	//ioutil.ReadAll(path + )

	PackageName := "controller"

	FileName := controllername

	FileName = strings.ToUpper(FileName[0:1]) + FileName[1:len(FileName)]
	//Create Controller
	//os.MkdirAll(path+"/output/b/controllers", 0766)
	f, _ := os.OpenFile(path+"/controllers/"+FileName+".go", os.O_CREATE|os.O_RDWR, 0766)
	result := ""
	Controllers = strings.Replace(Controllers, "{{packageName}}", "controller", -1)
	Controllers = strings.Replace(Controllers, "{{controllerName}}", FileName, -1)
	result += Controllers

	f.WriteString(result)
	ReadRouter(FileName, flags, PackageName)
	f.Close()
}
